const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json()) //解析客户端发送的JSON请求体，解析后会挂载到req.body上，访问解析后的数据
app.get("/api1", (req, res) => {
    res.json({
        success: true,
        data: {
            a: 1,
            b: 2,
            c: 3
        }
    })
})

app.post("/api1", (req, res) => {
    const body = req.body
    console.log('body is',body)
    res.json({
        success: true,
        data: {
            a: 1,
            b: 2,
            c: 3
        },
        username: body.username,
        password: body.password
    })
})

app.get("/detail", (req, res) => {
    const { id, name } = req.query; //查询detail?id=?的值，解构赋值
     console.log(id)
    console.log('name is',name)
    if (id === '1') {
        res.json({
            success: true,
            data: {
                title: "这是id1的title",
                content: "这是id1de content"
            }
        })
    }
    if (id === '2') {
        res.json({
            success: true,
            data: {
                title: "这是id2的title",
                content: "这是id2de content"
            }
        })
    }
    if (id === '3') {
        res.json({
            success: true,
            data: {
                title: "这是id3的title",
                content: "这是id3de content"
            }
        })
    }
})

app.listen(8000, (err) => {
    if (err) {
        console.error("启动失败")
    } else {
        console.log("启动成功，端口8000")
    }
});
